package com.xiaozhichao.javaapi.springcirculardependency;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class Spring {
    private static Map<String,Object> cache = new HashMap<String,Object>();
    private static int sum = 0;

    public static <T> T getBean(Class<T> clazz){
        sum ++ ;
        String className = clazz.getSimpleName().toLowerCase();
        if(cache.containsKey(className)){
            return (T) cache.get(className);
        }
        Object object = null;
        try {
            object = clazz.getDeclaredConstructor().newInstance();
            cache.put(className,object);
            Field[] fields = object.getClass().getDeclaredFields();
            for(Field field : fields){
                field.setAccessible(true);
                Class<?> classField = field.getType();
                String classNameField = classField.getSimpleName().toLowerCase();
                field.set(object,
                        cache.containsValue(classNameField)?cache.get(classNameField):getBean(classField));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) object;
    }

    public static void main(String[] args) {
        A a = Spring.getBean(A.class);
        B b = Spring.getBean(B.class);
        System.out.println(a.getB() == b);
        System.out.println(b.getA() == a);
        System.out.println(Spring.sum);
    }
}
